<template>
<!-- http://localhost:10001/#/purchase/purchasenoteEdit/311 -->
  <div class="purchasenote_add">
    <el-main>
      <el-tabs value="first">
        <el-tab-pane label="收货信息" name="first">
          <div class="newOrder-address">
            <span>收货人：{{ procurementParams.customer_name }}</span>
            <span>联系电话：{{ procurementParams.customer_phone }}</span>
            <span>收货地址：{{ procurementParams.customer_addr }}</span>
            <!-- <div>预计收货时间：{{ procurementParams.expect_time }}</div> -->
          </div>

          <!-- 顶部选项 -->
          <!-- <el-row :gutter="10">
            <el-col :span="2">
              <div style="margin-top: 7px; text-align: right">
                <span style="color: red">*</span>
                类型
              </div>
            </el-col>
            <el-col :span="3">
              <el-select v-model="sclxxz" placeholder="请选择">
                <el-option
                  v-for="item in sclx"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="3">
              <el-select v-model="cgryOrgysxz" filterable placeholder="请选择">
                <el-option
                  v-for="(item, i) in cgryOrgys"
                  :key="i"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="2">
              <div style="margin-top: 7px; text-align: right">仓库</div>
            </el-col>
            <el-col :span="3">
              <el-select v-model="cklxxz" placeholder="请选择">
                <el-option
                  v-for="(item, i) in cklx"
                  :key="i"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="2">
              <div style="margin-top: 7px; text-align: right">
                <span style="color: red">*</span>
                计划交货日期
              </div>
            </el-col>
            <el-col :span="4">
              <el-date-picker
                type="date"
                v-model="jhdate"
                value-format="yyyy-MM-dd"
                format="yyyy 年 MM 月 dd 日"
                placeholder="选择日期"
              ></el-date-picker>
            </el-col>
            <el-col :span="2">
              <div style="margin-top: 7px; text-align: right">排序方式</div>
            </el-col>
            <el-col :span="3">
              <el-select v-model="pxfsxz" placeholder="请选择">
                <el-option
                  v-for="item in pxfs"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-col>
          </el-row> -->
          <!-- <div style="margin: 5px 0">单据来源:</div> -->
          <!-- <div v-show="isshow"> -->
          <div>
            <!-- <el-row>
              <el-col :span="3">
                <div
                  style="
                    text-align: center;
                    font-size: 13px;
                    line-height: 30px;
                    color: #1890ff;
                    border-bottom: 2px solid #1890ff;
                  "
                >
                  采购单商品清单
                </div>
              </el-col>
            </el-row> -->
            <!-- <el-row
              :gutter="10"
              style="border-top: 1px solid #d8d8d8; padding-top: 10px"
            >
              <el-col :span="1">
                <div style="margin-top: 7px; text-align: right">商品</div>
              </el-col>
              <el-col :span="5"> -->
            <!-- <el-select v-model="shoppingres" filterable :filter-method="searchshopping" placeholder="请选择"> -->
            <!-- <el-popover
                    placement="right"
                    width="400"
                    trigger="click"> -->

            <!-- <el-select v-model="shoppingres" filterable :filter-method="searchshopping" placeholder="请选择">
                        <el-option v-for="(item,i) in shoppingName" :key="i" :label="item.name"
                            placeholder="请选商品名/助记码/编码/别名/关键字" :value="item.name">
                          </el-option>
                      </el-select> -->

            <!-- <el-autocomplete
                  v-model="shoppingres"
                  :fetch-suggestions="searchshoppinginput"
                  placeholder="请输入内容"
                  @select="handleSelect"
                ></el-autocomplete> -->

            <!-- <el-autocomplete
          class="inline-input search-input"
          v-model="shoppingres"
          ref="autocomplete"
          :fetch-suggestions="searchshoppinginput"
          placeholder="请输入您需要检索资源名称或者中文"
          @keyup.enter.native="searchAssets($event)"
          :trigger-on-focus="false"
          @select="handleSelect"
        >
          <el-button @click="searchAssets" slot="append">搜 索</el-button>
        </el-autocomplete> -->

            <!-- <el-input placeholder="请输入内容" v-model="input" clearable>
                </el-input> -->
            <!-- <el-option v-for="(item,i) in shoppingName" :key="i" :label="item.name"
                    placeholder="请选商品名/助记码/编码/别名/关键字" :value="item.name">
                  </el-option> -->
            <!-- <div style="width: 400px;height: 300px;position: absolute;z-index: 9;background-color: #bfa;transform: translateY(10px);">

                </div> -->
            <!-- </el-popover> -->

            <!-- </el-select> -->
            <!-- </el-col> -->
            <!-- <el-col :span="1">
                <el-button @click="searchfunc" type="primary">搜索</el-button>
              </el-col> -->
            <!-- <el-col :span="3">
                <div style="margin-top: 7px; text-align: right">数量</div>
              </el-col>
              <el-col :span="5">
                <el-input
                  v-model="numberfunc"
                  placeholder="请输入数量"
                ></el-input>
              </el-col>
              <el-col :span="3">
                <el-button type="primary" @click="addfunc">添加</el-button>
              </el-col>
            </el-row> -->
            <!-- <div
              style="text-align: right; margin-bottom: 20px; margin-top: -20px"
            >
              <el-button @click="drawer = true">表头设置</el-button>
            </div> -->
            <el-drawer title="选择表头显示列" size="15%" :visible.sync="drawer">
              <div
                v-for="(res, i) in tablecheckAll"
                :key="i"
                style="padding: 10px; line-height: 30px"
              >
                <el-checkbox
                  :disabled="tableforbid.indexOf(res) !== -1"
                  v-model="tablecheckeds"
                  :label="res"
                >
                  {{ res }}
                </el-checkbox>
              </div>
            </el-drawer>

            <el-table
              border
              :data="tableData"
              style="width: 100%; margin-bottom: 10px"
            >
              <el-table-column
                v-if="tablecheckeds.indexOf('序号') > -1"
                prop="date"
                label="序号"
                type="index"
                width="50"
              ></el-table-column>
              <el-table-column
                v-if="tablecheckeds.indexOf('商品图片') > -1"
                prop="name"
                label="商品图片"
                width="120"
              >
                <template slot-scope="scope">
                  <img :src="scope.row.image_path" alt="购物车" />
                  <!-- {{scope.row}} -->
                </template>
              </el-table-column>
              <el-table-column
                prop="product_name"
                v-if="tablecheckeds.indexOf('商品') > -1"
                label="商品"
              ></el-table-column>
              <el-table-column
                prop="unit"
                v-if="tablecheckeds.indexOf('单位') > -1"
                label="单位"
              ></el-table-column>
              <!-- <el-table-column
                prop="wu"
                v-if="tablecheckeds.indexOf('近一次采购') > -1"
                label="近一次采购"
              ></el-table-column> -->
              <!-- <el-table-column
                prop="wu"
                v-if="tablecheckeds.indexOf('采购询价') > -1"
                label="采购询价"
                width="120"
              ></el-table-column>
              <el-table-column
                prop="wu"
                v-if="tablecheckeds.indexOf('市场参考价') > -1"
                label="市场参考价"
                width="100"
              ></el-table-column> -->
              <el-table-column
                prop="price"
                v-if="tablecheckeds.indexOf('市场价') > -1"
                label="市场价"
                width="120"
              >
                <template slot-scope="scope">
                  {{ scope.row.shelf_price | filterMoney }}
                  <!-- <el-input v-model="result" placeholder="请输入内容"></el-input> -->
                  <!-- <input style="width: 100%;" v-model="scope.row.procurementprice" type="number"> -->
                </template>
              </el-table-column>
              <el-table-column
                prop="qty"
                v-if="tablecheckeds.indexOf('数量') > -1"
                label="数量"
                width="120"
              >
                <template slot-scope="scope">
                  <el-input
                    @input="inpunValueChange(scope.row, scope.$index)"
                    :disabled="scope.row.status != 2"
                    v-model.number="scope.row.qty"
                    type="number"
                    oninput="value=value.replace(/^(0+)|[^\d]+/g,'')"
                    placeholder="请输入内容"
                    v-if="scope.row.qty_delivery == null"
                  ></el-input>
                  <el-input
                    v-else
                    disabled
                    v-model.number="scope.row.qty_delivery"
                    type="number"
                    oninput="value=value.replace(/^(0+)|[^\d]+/g,'')"
                    placeholder="请输入内容"
                  ></el-input>
                  <!-- <el-input v-model="scope.row.topurchasequantity"></el-input> -->
                </template>
              </el-table-column>
              <el-table-column
                v-if="tablecheckeds.indexOf('总金额') > -1"
                label="总金额"
                width="120"
              >
                <template slot-scope="scope">
                  <div v-if="scope.row.qty_delivery == null">
                    {{ scope.row.shelf_price * scope.row.qty | filterMoney }}
                  </div>
                  <div v-else>
                    {{ scope.row.shelf_price * scope.row.qty_delivery | filterMoney }}
                  </div>
                </template>
              </el-table-column>
              <!-- <el-table-column
                prop="remarks"
                v-if="tablecheckeds.indexOf('备注') > -1"
                label="备注"
                width="120"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.remarks"
                    placeholder="请输入内容"
                  ></el-input>
                </template>
              </el-table-column> -->
              <el-table-column fixed="right" label="操作">
                <template slot-scope="scope">
                  <el-button
                    v-permissions="['Admin', 'supplier','SupplierManagement']"
                    v-if="scope.row.status == 1 && statusOfGoods != 0 "
                    @click="clickToConfirmBtn(scope.row)"
                    type="text"
                    size="small"
                  >
                    确认
                  </el-button>
                  <el-button
                    v-if="scope.row.status == 2"
                    @click="sentBtn(scope.row, scope.$index)"
                    type="text"
                    size="small"
                    v-show="controlSentBtn(scope.row.status)"
                    v-permissions="['Admin', 'supplier','SupplierManagement']"
                  >
                    发货
                  </el-button>
                  <el-button
                    v-permissions="['Admin', 'supplier','SupplierManagement']"
                    v-if="scope.row.status == 1 && statusOfGoods != 0"
                    @click="deleteRow(scope.row)"
                    type="text"
                    size="small"
                  >
                    取消
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div
              style="
                width: 100%;
                margin-bottom: 10px;
                text-align: right;
                padding-right: 20px;
              "
            >
              合计(含税) :
              <span style="color: red">￥{{ goodsPricecont.toFixed(2) }}</span>
            </div>
            <!-- <div style="margin-bottom: 40px">
              备注：
              <el-input v-model="beizhus" placeholder="请输入内容"></el-input>
            </div> -->
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-main>
    <div
      style="
        position: fixed;
        bottom: 0;
        background-color: #ffffff;
        width: 100%;
        line-height: 80px;
        z-index: 9;
      "
    >
      <!-- <el-button
        @click="savefunc"
        v-if="$route.meta.title != '详情'"
        style="margin-left: 40px"
        type="primary"
      >
        保存
      </el-button> -->
      <el-button @click="returnpre" type="primary" plain>返回列表</el-button>
    </div>
    <el-dialog title="提示" :visible.sync="confirmDialogVisible" width="30%">
      <span>是否确认该商品?</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="confirmDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmRowBtn">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="cancelDialogVisible" width="30%">
      <span>是否取消该商品?</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="cancelDialogRowBtn">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="deliveryDialogRowBtn" width="30%">
      <span>是否确认发货?</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deliveryDialogRowBtn = false">取 消</el-button>
        <el-button type="primary" @click="deliveryGoods()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getShopping,
  getwarehouse,
  addfuntoo,
  addfun,
  getitemlist,
  setorderedit,
  setorderitemedit,
  delivery,
  cancelOrder,
  confirmOrder,
  rebackGoods,
} from '@/api/purchase/purchasenote.js'
import { getbuyerAll } from '@/api/purchase/buyerapi.js'
import { getsupplierAll } from '@/api/purchase/supplierapi.js'
import paramsData from '@/utils/data.js'
import { status } from 'nprogress'
export default {
  computed: {
    goodsPricecont() {
      let cont = 0
      this.tableData.forEach((i) => {
        if (i.qty_delivery == null) {
          cont = cont + i.qty * i.shelf_price
        } else {
          cont = cont + i.qty_delivery * i.shelf_price
        }
      })
      return cont / 100
    },
  },
  filters: {
    filterMoney(num) {
      return (num / 100).toFixed(2)
    }
  },
  watch: {
    async sclxxz(val, newval) {
      if (val == '市场自采') {
        let res = await getbuyerAll({})
        this.cgryOrgys = res.list
      } else {
        let res = await getsupplierAll({})
        this.cgryOrgys = res.list
      }
    },
    cgryOrgysxz(val, newval) {
      if (this.cklxxz != '' && this.jhdate != '' && this.pxfsxz != '') {
        this.isshow = true
      }
    },
    cklxxz(val, newval) {
      if (
        this.cklxxz != '' &&
        this.jhdate != '' &&
        this.pxfsxz != '' &&
        this.cgryOrgysxz !== ''
      ) {
        this.isshow = true
      }
    },
    jhdate(val, newval) {
      if (
        this.cklxxz != '' &&
        this.jhdate != '' &&
        this.pxfsxz != '' &&
        this.cgryOrgysxz !== ''
      ) {
        this.isshow = true
      }
    },
    pxfsxz(val, newval) {
      if (
        this.cklxxz != '' &&
        this.jhdate != '' &&
        this.pxfsxz != '' &&
        this.cgryOrgysxz !== ''
      ) {
        this.isshow = true
      }
    },
  },
  data() {
    return {
      trrigerShelf_price: null, // 上架价格
      trrigerShelf_total: null, // 上架总价
      showPurchased: false,
      sentGood: {},
      deliveryDialogRowBtn: false,
      confirmDialogVisible: false,
      cancelDialogVisible: false,
      confirmRowDataFilter: {},
      cancelRowDataFilter: {},
      tablecheckAll: [
        '序号',
        '商品图片',
        '商品',
        '单位',
        '近一次采购',
        '采购询价',
        '市场参考价',
        '市场价',
        '数量',
        '总金额',
        '备注',
      ],
      tablecheckeds: [
        '序号',
        '商品图片',
        '商品',
        '单位',
        '近一次采购',
        '采购询价',
        '市场参考价',
        '市场价',
        '数量',
        '总金额',
        '备注',
      ],
      tableforbid: ['序号', '商品图片', '商品', '市场价', '数量', '总金额'],
      drawer: false,
      shoppingName: '', //商品名字
      shoppingres: '', //商品结果
      sclx: ['市场自采', '供应商直供'], //市场类型
      sclxxz: '', //最终选择结果
      cklx: '', //仓库类型
      cklxxz: '', //仓库最终选择类型
      person: '', //人员选择
      cgryOrgys: '', //采购人员或供应商
      cgryOrgysxz: '', //采购人员或供应商选择
      jhdate: '', //交货日期
      pxfs: ['手动新增排序', '按一二级分类排序'], //排序
      pxfsxz: '', //排序方式选择
      numberfunc: 1, //数量
      isshow: false,
      tableData: [],
      data: [],
      num: 0,
      craet: {},
      totleprice: '0', //总金额
      beizhus: '', //备注
      procurementParams: {},
      statusOfGoods:null,
    }
  },
  created() {
    this.statusOfGoods =this.$route.query.ShowStatus
    console.log(this.statusOfGoods,'1842')
    //获取仓库列表
    this.getWareHouseList()
    //获取商品table数据
    this.getGoodsTableData()
  },
  mounted() {
    this.searchshopping()
  },
  methods: {
    inpunValueChange(data, index) {
      if (this.tableData[index].qty > this.data[index].qty) {
        this.$message.error('不能超过下单数量')
        this.tableData[index].qty = this.data[index].qty
        return false
      }
    },
    //--------------------------------------------------------获取商品table数据。
    async getGoodsTableData() {
      this.procurementParams = JSON.parse(sessionStorage.getItem('procurement'))
      let ordersId = this.$route.params.id //必传参数订单ID。
      let res = await getitemlist(20, 1, ordersId)
      this.data = JSON.parse(JSON.stringify(res.list))
      this.tableData = JSON.parse(JSON.stringify(res.list))
      this.beizhus = res.list[0].remarks
    },
    //--------------------------------------------------------仓库select。
    async getWareHouseList() {
      let ckres = await getwarehouse({})
      this.cklx = ckres.data.list

      // if (this.$route.params.id) {
      //   this.isshow = true
      //   let data = {
      //     id: this.$route.params.id,
      //   }
      // let resedit = await getList(1, 1, data)
      // let gitres = resedit.list[0]
      // console.log('第一个接口', resedit)
      // this.beizhus = gitres.remarks
      // this.jhdate = gitres.delivery_date
      // this.sclxxz = gitres.type
      // this.cklx.forEach((item) => {
      //   if (item.id == gitres.warehouse_id) {
      //     this.cklxxz = item.name
      //   }
      // })
      // if (this.sclxxz == '市场自采') {
      //   let res = await getbuyerAll({})
      //   this.cgryOrgys = res.list
      // } else {
      //   let res = await getsupplierAll({})
      //   this.cgryOrgys = res.list
      // }
      // if (gitres.purchaser_name) {
      //   this.cgryOrgysxz = gitres.purchaser_name
      // } else {
      //   this.cgryOrgysxz = gitres.supplier_name
      // }
      //--------------------------------------------------------采购详情table表格。
      // let shoppingres = await getitemlist(20, 1, gitres.id)
      // console.log('第二个接口', shoppingres)
      // let cont = 0
      // shoppingres.list.forEach(async (item) => {
      //   let data = {
      //     name: item.product_name,
      //   }
      //   console.log(shoppingres, '0000000000000000')
      // let res = await getShopping(data)
      // console.log('第三个接口', res)
      // res = shoppingres.list

      // let newarr = res.map((items) => {
      //   cont = cont + parseFloat(item.subtotal / 100.0)
      //   return {
      //     ...items,
      //     procurementprice: item.price / 100,
      //     editid: item.id,
      //     topurchasequantity: item.qty,
      //     purchaseamount: parseFloat(item.subtotal / 100.0),
      //     remark: item.remarks,
      //   }
      // })
      //这里的代码导致下单时，订单详情中的商品列表重复。
      // this.tableData = shoppingres.list
      // newarr.forEach((e) => {
      //   // this.tableData.push(e)
      //   console.log('this.tableData', this.tableData)
      // })
      // this.totleprice = cont
      // })
      // }
    },
    async cancelDialogRowBtn() {
      const res = await setorderitemedit(this.cancelRowDataFilter)
      if (res.status == 200) {
        this.$message.success('操作成功')
        this.getGoodsTableData()
        this.cancelDialogVisible = false
        this.confirmSuccessBtns()
      } else {
        this.$message.success('操作失败')
      }
    },
    async confirmSuccessBtns() {
      // let state = 0
      // if (this.tableData.length == 1) {
      //   state = 6
      // } else {
      //   let a = 0
      //   this.tableData.forEach((e) => {
      //     if (e.status == 6) {
      //       a = a + 1
      //     }
      //   })
      //   if (a == this.tableData.length - 1) {
      //     state = 6
      //   } else {
      //     state = 7
      //   }
      // }
	  
      // const res = await setorderedit({
      //   id: this.$route.params.id,
      //   status: 0,
      // })
    },
    clickToConfirmBtn(data) {
      this.confirmDialogVisible = true
      this.confirmRowDataFilter.status = 2
      this.confirmRowDataFilter.id = data.id
    },
    async confirmRowBtn() {
      const res = await setorderitemedit(this.confirmRowDataFilter)
      if (res.status == 200) {
        this.$message.success('操作成功')
        this.getGoodsTableData()
        this.confirmDialogVisible = false
        // this.confirmSuccessBtn()
      } else {
        this.$message.success('操作失败')
      }
    },
    // async confirmSuccessBtn() {
    //   const res = await setorderedit({
    //     id: this.$route.params.id,
    //     status: 2,
    //   })
    // },
    controlSentBtn(info) {
      if (info == 3) {
        return false
      } else {
        return true
      }
    },
    async searchshoppinginput(val, cb) {
      let data = ''
      if (isNaN(val)) {
        data = {
          name: val,
          // code: val
        }
      } else {
        data = {
          code: val,
          // code: val
        }
      }
      // if()
      let res = await getShopping(data)
      if (res.data.list.length == 0) {
        return
      } else {
        this.shoppingName = res.data.list
        let datalist = []
        res.data.list.forEach((item) => {
          let datalistres = {
            value: item.name,
          }
          datalist.push(datalistres)
        })
        cb(datalist)
      }
      // console.log("resssaaaaaaaa", res);
      //   console.log('进来')
      //   // data = [ { "value": "三全鲜食（北新泾店）", "address": "长宁区新渔路144号" },
      //   // { "value": "Hot honey 首尔炸鸡（仙霞路）", "address": "上海市长宁区淞虹路661号" },
      //   // { "value": "新旺角茶餐厅", "address": "上海市普陀区真北路988号创邑金沙谷6号楼113" },
      //   // { "value": "泷千家(天山西路店)", "address": "天山西路438号" },
      //   // { "value": "胖仙女纸杯蛋糕（上海凌空店）", "address": "上海市长宁区金钟路968号1幢18号楼一层商铺18-101" },
      //   // { "value": "贡茶", "address": "上海市长宁区金钟路633号" },]
      //   cb(data)
      //   console.log(data)
      // this.shoppingName = res.data.list
    },
    handleSelect(val) {
    },
    async search() {},
    async searchshopping(val) {
      let data = ''
      if (isNaN(val)) {
        data = {
          name: val,
          // code: val
        }
      } else {
        data = {
          code: val,
          // code: val
        }
      }
      // if()
      let res = await getShopping(data)
      this.shoppingName = res.data.list
    },
    async savefunc() {
      // 获取采购员或供应商
      let purchaserId = ''
      let supplierId = ''
      let warehouseId = '' //仓库id
      if (this.sclxxz == '市场自采') {
        this.cgryOrgys.forEach((item) => {
          if (this.cgryOrgysxz == item.name) {
            purchaserId = item.id
          }
        })
      } else {
        this.cgryOrgys.forEach((item) => {
          if (this.cgryOrgysxz == item.name) {
            supplierId = item.id
          }
        })
      }

      this.cklx.forEach((item) => {
        if (item.name == this.cklxxz) {
          warehouseId = item.id
        }
      })

      if (this.$route.params.id) {
        let timestamp = Date.parse(new Date()) / 1000
        let data = {
          id: this.$route.params.id,
          wsId: '1',
          warehouseId: warehouseId,
          type: this.sclxxz,
          purchaserId: purchaserId,
          supplierId: supplierId,
          total: this.totleprice * 100,
          status: '1',
          deliveryDate: this.jhdate,
          remarks: this.beizhus,
          utime: timestamp,
          uuser: 'tom',
        }
        // let res = await setorderedit(data)

        this.tableData.forEach(async (item, i) => {
          let timestamp = Date.parse(new Date()) / 1000
          let dataobject = {
            id: item.editid,
            qty: item.topurchasequantity,
            unit: item.unit,
            price: item.procurementprice * 100,
            subtotal: parseInt(item.purchaseamount * 100),
            remarks: item.remark,
            timeDelivery: timestamp,
            status: '1',
          }
          let r = await setorderitemedit(dataobject)
        })
        this.$message({
          message: '修改成功',
          type: 'success',
        })
      } else {
        let data = {
          wsId: '1', //站点
          type: this.sclxxz, //市场类型
          deliveryDate: this.jhdate, //计划收货日期
          remarks: this.beizhus, //备注
          warehouseId: warehouseId, //仓库id
          purchaserId: purchaserId, //采购员id
          supplierId: supplierId, //供应商id
          total: this.totleprice * 100, //金额 分为单位
          status: '1', //订单状态
        }
        let res = await addfun(data)
        let orderid = res.data.orderid
        this.tableData.forEach(async (item, i) => {
          let timestamp = Date.parse(new Date()) / 1000

          let dataobject = {
            orderId: orderid,
            productName: item.name,
            productId: item.id,
            qty: item.topurchasequantity,
            unit: item.unit,
            price: item.procurementprice * 100,
            subtotal: item.purchaseamount * 100,
            remarks: item.remark,
            ctime: timestamp,
          }
          let r = await addfuntoo(dataobject)
        })
        this.$message({
          message: '保存成功',
          type: 'success',
        })
        // 保存成功准备跳转
      }

      this.$router.push('/purchase/purchasenote')
    },
    returnpre() {
      this.$router.push('/purchase/purchasenote')
    },
    deleteRow(row) {
      this.cancelDialogVisible = true
      this.cancelRowDataFilter.id = row.id
      this.cancelRowDataFilter.status = 0
    },

    async sentBtn(data, index) {
      if (this.tableData[index].qty > this.data[index].qty) {
        this.$message.error('不能超过下单数量')
        this.tableData[index].qty = this.data[index].qty
        return false
      }
      let num = 0
      if (this.tableData[index].qty < this.data[index].qty) {
        num = this.data[index].qty - this.tableData[index].qty
        this.num = num
        this.trrigerShelf_price = data.shelf_price
        this.trrigerShelf_total = data.shelf_price * this.num
        this.craet = data
      }
      var time = new Date()
      this.sentGood.timeDelivery = time.toLocaleDateString().replace(/\//g, '-')
      this.sentGood.deliveryDate = time.toLocaleDateString().replace(/\//g, '-')
      this.sentGood.qtyDelivery = this.tableData[index].qty
      this.sentGood.id = data.id
      this.sentGood.status = 3
      this.deliveryDialogRowBtn = true
    },
    async deliveryGoods() {
      if (this.num != 0) {
        let timestamp = Date.parse(new Date()) / 1000
        let num = this.num
        let data = this.craet
        const res = await rebackGoods({
          orderId: this.procurementParams.sales_orderid,
          productName: data.product_name,
          productId: data.product_id,
          qty: num,
          unit: data.unit,
          price: data.price,
          subtotal: num * data.price,
          remarks: '供应商缺货',
          ctime: timestamp,
          customerId: this.procurementParams.customer_id,
          status: 2,
          salesItemid: data.sales_itemid,
          shelfTotal: this.trrigerShelf_total,
          shelfPrice: this.trrigerShelf_price,
        })
      }
      this.showPurchased = true
      this.deliveryDialogRowBtn = false
      const ress = await delivery(this.sentGood)
      if (ress.status == 200) {
        this.$message({
          type: 'success',
          message: '操作成功',
        })
        this.getGoodsTableData()
        // const resss = await cancelOrder(sent)
        this.sentGoodsSuccessBtns()
      } else {
        this.$message({
          type: 'error',
          message: '操作失败',
        })
      }
    },
    async sentGoodsSuccessBtns() {
      let state = 0
      // if (this.tableData.length == 1) {
      //   state = 3
      // } else {
      //   let a = 0
      //   this.tableData.forEach((e) => {
      //     if (e.status == 3) {
      //       a = a + 1
      //     }
      //   })
      //   console.log(a, '11111111111')
      //   if (a == this.tableData.length - 1) {
      //     state = 3
      //   } else {
      //     //部分发货-生成退货单
      //     const res = (state = 4)
      //   }
      // }
      // const res = await setorderedit({
      //   id: this.$route.params.id,
      //   status: state,
      // })
    },
    querySearchAsync(a, b) {},

    addfunc() {
      this.seaerchdata = ''

      if (this.shoppingres == '') {
        return
      }

      if (this.shoppingName.length == 0) {
        this.$message({
          message: '没有该商品',
          type: 'error',
        })
        return
      }
      let res = this.shoppingName.filter((res) => {
        return res.name == this.shoppingres
      })
      let tablelength = this.tableData.length
      for (let i = 0; i < tablelength; i++) {
        if (this.tableData[i].name == res[0].name) {
          this.$message({
            message: '该商品已添加',
            type: 'error',
          })
          return
        }
      }

      this.shoppingres = ''
      this.searchshopping()
      let newarr = res.map((item) => {
        return {
          ...item,
          procurementprice: 0.0,
          topurchasequantity: this.numberfunc,
          purchaseamount: 0.0,
        }
      })
      newarr.forEach((e) => {
        this.tableData.push(e)
      })
    },
  },
}
</script>

<style lang="scss">
.purchasenote_add .el-date-editor.el-input {
  width: 100% !important;
}

.purchasenote_add .cell img {
  width: 50px;
  /* height: 100%; */
}

.purchasenote_add .cell input {
  padding-right: 0;
}

.purchasenote_add #el-drawer__title {
  border-bottom: 1px solid #f3f3f3;
}
.newOrder-address {
  width: 100%;
  padding: 10px;
  text-align: left;
  border-bottom: 8px solid #f5f5f5;
  font-size: 16px;
  line-height: 24px;
}

.newOrder-address > span {
  margin-right: 15px;
}
/*  .purchasenote_add .el-main{
    height: 100% !important;
    overflow: auto !important;
  } */
</style>
